package com.yangmin.springcloud.controller;

import cn.hutool.core.util.IdUtil;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.yangmin.springcloud.service.PaymentHystrixService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Slf4j
public class PaymentHystrixController {
    @Autowired
    private PaymentHystrixService paymentHystrixService;

    @GetMapping("/payment/hystrix/ok/{id}")
    public String paymentHistrixInfo_OK(@PathVariable("id") Integer id) {
        String result = paymentHystrixService.paymentHystrixService_Ok(id);
        log.info(result);
        return result;
    }

    @GetMapping("/payment/hystrix/outtime/{id}")
    public String paymentHistrixInfo_Outtime(@PathVariable("id") Integer id) {
        String result = paymentHystrixService.paymentHystrixService_Outtime(id);
        log.info(result);
        return result;
    }


    ///////////////////////////////    服务熔断   //////////////////////////////////////

    @GetMapping("/payment/hystrix/breaker/{id}")
    @HystrixCommand(fallbackMethod = "paymentHystrixCircuitBreakerMethod", commandProperties = {
            @HystrixProperty(name = "circuitBreaker.enabled", value = "true"),
            @HystrixProperty(name = "circuitBreaker.requestVolumeThreshold", value = "10"),
            @HystrixProperty(name = "circuitBreaker.sleepWindowInMilliseconds", value = "10000"),
            @HystrixProperty(name = "circuitBreaker.errorThresholdPercentage", value = "60")})
    public String paymentCircuitBreakerInfo(@PathVariable("id") Integer id) {
        if (id < 0) {
            throw new RuntimeException("id 不能为负数");
        }
        return paymentHystrixService.paymentCircuitBreaker(id);
    }

    // 服务降级方法与被调用方法之间的参数应该相同
    public String paymentHystrixCircuitBreakerMethod(Integer id) {
        return "抱歉！！ id 不能为负数，请稍后再试！！ 哎呀";
    }

}
